import React from 'react'
import PropTypes from 'prop-types'
import { inject, observer } from 'mobx-react'
import { Redirect } from 'react-router-dom'
import queryString from 'query-string'
import TextField from '@material-ui/core/TextField'
import Button from '@material-ui/core/Button'
import { withStyles } from '@material-ui/core/styles'
import loginStyles from './styles/login-style'
import UserWrapper from './user'

@inject(stores => ({
  appState: stores.appState,
  user: stores.appState.user,
}))
@observer
class Login extends React.Component {
  state = {
    accesstoken: '',
    helperText: '',
  }

  handleInput = (e) => {
    this.setState({
      accesstoken: e.target.value.trim(),
    })
  }

  handleLogin = () => {
    const { appState } = this.props
    const { accesstoken } = this.state

    if (!accesstoken) {
      return this.setState({
        helperText: '请填写',
      })
    }
    this.setState({
      helperText: '',
    })

    return appState.login(accesstoken)
  }

  getFrom = () => {
    const { location } = this.props
    const query = queryString.parse(location.search)
    return query.from || '/user/info'
  }

  render() {
    const { classes, user } = this.props
    const { accesstoken, helperText } = this.state
    const from = this.getFrom()

    if (user.isLogin) {
      return (
        <Redirect to={ from } />
      )
    }

    return (
      <UserWrapper>
        <div className={ classes.root }>
          <TextField
            label="请输入Cnode AccessToken"
            placeholder="请输入Cnode AccessToken"
            required
            className={ classes.input }
            helperText={ helperText }
            value={ accesstoken }
            onChange={ this.handleInput }
          />
          <Button
            variant="contained"
            className={ classes.loginButton }
            color="inherit"
            onClick={ this.handleLogin }
          >
            Login
          </Button>
        </div>
      </UserWrapper>
    )
  }
}

Login.wrappedComponent.propTypes = {
  appState: PropTypes.object.isRequired,
  user: PropTypes.object.isRequired,
}

Login.propTypes = {
  classes: PropTypes.object.isRequired,
  location: PropTypes.object.isRequired,
}

export default withStyles(loginStyles)(Login)
